package nz.ac.massey.doi_information_extractor.gui;

import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;


import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import nz.ac.massey.doi_information_extractor.data.Author;
import nz.ac.massey.doi_information_extractor.database.DatabaseInterface;


@SuppressWarnings("serial")
public class SelectAuthorDialog extends JDialog implements ActionListener, ListSelectionListener{

    private static SelectAuthorDialog dialog;
    private static Author selectedAuthor;
    private JButton selectButton, cancelButton, createButton, editButton;
    private JTextArea inputAuthorTextArea, selectedAuthorTextArea;
    private JList authorJList;
    private Author inputAuthor;
    private ArrayList<Author> authorList;
    private DatabaseInterface database;

    public static Author showDialog(Component frameComp, Author author, DatabaseInterface database){
		Frame frame = JOptionPane.getFrameForComponent(frameComp);

		dialog = new SelectAuthorDialog(frame, author, database);
		dialog.setVisible(true);

		dialog = null;

		if(selectedAuthor != null)
			try {
				database.writeAuthor(selectedAuthor);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	return selectedAuthor;
    }

    public SelectAuthorDialog(Frame frame, Author author, DatabaseInterface database){
    	super(frame, "Select Author", true);

    	this.inputAuthor = author;
    	this.database = database;
    	init();
    }

    private void setAuthorJList(){
    	try {
			authorList = database.getAuthors();
		} catch (SQLException e) {
			authorList = null;
			return;
		}

		sortAuthorList(authorList);

		String[] authorsStringArray = new String[authorList.size()];

		for(int i = 0; i < authorList.size(); i++){
			authorsStringArray[i] = authorList.get(i).getAuthorLastName() + ", " + authorList.get(i).getAuthorFirstName().charAt(0);
		}

		authorJList.setListData(authorsStringArray);
		authorJList.setSelectedIndex(0);
    }

	private void init(){

        JPanel mainPanel = new JPanel();
        JScrollPane jScrollPane1 = new JScrollPane();
        inputAuthorTextArea = new JTextArea();
        inputAuthorTextArea.setEditable(false);


        JScrollPane jScrollPane2 = new JScrollPane();
        authorJList = new JList();
        authorJList.addListSelectionListener(this);

        JScrollPane jScrollPane3 = new JScrollPane();
        selectedAuthorTextArea = new JTextArea();
        selectedAuthorTextArea.setEditable(false);

        selectButton = new JButton("Select");
        selectButton.addActionListener(this);

        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(this);

        createButton = new JButton("Create New");
        createButton.addActionListener(this);

        editButton = new JButton("Edit");
        editButton.addActionListener(this);

        inputAuthorTextArea.setColumns(20);
        inputAuthorTextArea.setRows(5);
        jScrollPane1.setViewportView(inputAuthorTextArea);

        jScrollPane2.setViewportView(authorJList);

        selectedAuthorTextArea.setColumns(20);
        selectedAuthorTextArea.setRows(5);
        jScrollPane3.setViewportView(selectedAuthorTextArea);

       GroupLayout mainPanelLayout = new GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2,GroupLayout.PREFERRED_SIZE, 150,GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3,GroupLayout.PREFERRED_SIZE, 187,GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(selectButton,GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                    .addComponent(createButton,GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                    .addComponent(editButton,GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                    .addComponent(cancelButton,GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3,GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(selectButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(createButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(editButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton))
                    .addComponent(jScrollPane2,GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                    .addComponent(jScrollPane1,GroupLayout.Alignment.TRAILING,GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
                .addContainerGap())
        );

        getContentPane().add(mainPanel);

        pack();


        setInputAuthor();
    	setAuthorJList();
	}

	private void setInputAuthor(){
		if(inputAuthor == null)
			return;

    	inputAuthorTextArea.append("Input Author \n\n");
    	inputAuthorTextArea.append("First name:\t" + inputAuthor.getAuthorFirstName() + "\n");
    	inputAuthorTextArea.append("Last name:\t" + inputAuthor.getAuthorLastName() + "\n");
    	inputAuthorTextArea.append("Type:\t" + inputAuthor.getAuthorType() + "\n");
    	inputAuthorTextArea.append("Department:\t" + inputAuthor.getDepartment() + "\n");
    	inputAuthorTextArea.append("Organisation:\t" + inputAuthor.getOrganisation() + "\n");
    	inputAuthorTextArea.append("Massey User ID:\t" + inputAuthor.getUserId() + "\n");
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == selectButton){
			selectedAuthor = authorList.get(authorJList.getSelectedIndex());
		}else if(e.getSource() == cancelButton){
			selectedAuthor = null;
		}else if(e.getSource() == createButton){
			selectedAuthor = CreateAuthorDialog.showDialog(this, inputAuthor, "New Author");
		}else if(e.getSource() == editButton){
			selectedAuthor = CreateAuthorDialog.showDialog(this, authorList.get(authorJList.getSelectedIndex()), "Edit Author");
		}
        this.setVisible(false);
		this.dispose();
	}

	@Override
	public void valueChanged(ListSelectionEvent arg0) {

		if(authorJList.getSelectedIndex() == -1)
			return;

		Author author = authorList.get(authorJList.getSelectedIndex());
		selectedAuthorTextArea.setText("");
		selectedAuthorTextArea.append("Selected Author \n\n");
		selectedAuthorTextArea.append("First name:\t" + author.getAuthorFirstName() + "\n");
		selectedAuthorTextArea.append("Last name:\t" + author.getAuthorLastName() + "\n");
		selectedAuthorTextArea.append("Type:\t" + author.getAuthorType() + "\n");
		selectedAuthorTextArea.append("Department:\t" + author.getDepartment() + "\n");
		selectedAuthorTextArea.append("Organisation:\t" + author.getOrganisation() + "\n");
		selectedAuthorTextArea.append("Massey ID:\t" + author.getUserId() + "\n");
	}

	/**
	 * Sorts a given list of authors into alphabetical order
	 * @param authors
	 */
	private void sortAuthorList(ArrayList<Author> authors){
		if(authors.size() <= 1)
			return;


		for (int index = 0; index < authors.size(); index++) {
			Author smallestAuthor = authors.get(index);
			int smallestIndex = index;

			for (int j = index; j < authors.size(); j++) {
				Author currentAuthor = authors.get(j);

				int lastComparison = currentAuthor.getAuthorLastName().compareTo(smallestAuthor.getAuthorLastName());
				if(lastComparison < 0){
					smallestAuthor = currentAuthor;
					smallestIndex = j;
				}else if(lastComparison == 0 ){
					int firstComparison = currentAuthor.getAuthorFirstName().compareTo(smallestAuthor.getAuthorFirstName());
					if(firstComparison < 0 ){
						smallestAuthor = currentAuthor;
						smallestIndex = j;
					}
				}
			}

			if(smallestIndex == index)
				continue;

			Author indexAuthor = authors.get(index);

			authors.set(smallestIndex, indexAuthor);
			authors.set(index, smallestAuthor);
		}

		authorList = authors;
	}
}
